package com.warmlight.voicepacket;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.multidex.MultiDexApplication;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.bumptech.glide.load.engine.cache.LruResourceCache;
import com.bumptech.glide.module.AppGlideModule;
import com.danikula.videocache.HttpProxyCacheServer;
import com.facebook.cache.disk.DiskCacheConfig;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechUtility;
import com.karumi.dexter.Dexter;
import com.lzy.ninegrid.NineGridView;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.warmlight.voicepacket.common.Constants;
import com.warmlight.voicepacket.data.eventbus.Login;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.http.LoggerInterceptor;
import com.warmlight.voicepacket.http.ResponseData;
import com.warmlight.voicepacket.utils.SPUtils;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import okhttp3.OkHttpClient;

public class MApplication extends MultiDexApplication {

    private static MApplication mInstance;

    private HttpProxyCacheServer proxy;


    @Override
    public void onCreate() {
        super.onCreate();
        //融云初始化
        RongIM.init(this);
//        RongIM.getInstance().setMessageAttachedUserInfo(true);
        RongIMClient.setConnectionStatusListener(new RongIMClient.ConnectionStatusListener() {
            @Override
            public void onChanged(ConnectionStatus connectionStatus) {
                switch (connectionStatus){

                    case CONNECTED://连接成功。

                        break;
                    case DISCONNECTED://断开连接。

                        break;
                    case CONNECTING://连接中。

                        break;
                    case NETWORK_UNAVAILABLE://网络不可用。

                        break;
                    case KICKED_OFFLINE_BY_OTHER_CLIENT://用户账户在其他设备登录，本机会被踢掉线
                        RongIM.getInstance().disconnect();
                        RongIM.getInstance().logout();
                        SPUtils.logout();
                        EventBus.getDefault().post(new Login(false));
                        showToast();
                        break;
                }
            }
        });
//        if (LeakCanary.isInAnalyzerProcess(this)) {
//            // This process is dedicated to LeakCanary for heap analysis.
//            // You should not init your app in this process.
//            return;
//        }
//        LeakCanary.install(this);
        // Normal app init code...
        mInstance = this;
        initOkhttpClient();
//        CrashHandler crashHandler = CrashHandler.getInstance();
//		crashHandler.init(this);

        //动态权限
        Dexter.initialize(this);
//RequestOptions

        //GlideBuilder

//        MobSDK.init(this);

        //友盟统计，传输日志未加密
        UMConfigure.init(this,UMConfigure.DEVICE_TYPE_PHONE,null);

        PlatformConfig.setWeixin("wxc6ca2739a1f349af", "242e172ae41dc25031c6ed398ad35511");
        //豆瓣RENREN平台目前只能在服务器端配置
        PlatformConfig.setQQZone("101481822", "e01a8cfb30f4f00a91fcb7bba6c46020");
//        UMConfigure.setEncryptEnabled(true);
        UMConfigure.setLogEnabled(false);
        ZhugeSDK.getInstance().init(this);
//        ZhugeSDK.getInstance().init(this,"16c710b2ca9b483493bfc871913c547a","default_channel");
//        ZhugeSDK.getInstance().openDebug();

        //初始化讯飞
        SpeechUtility.createUtility(getApplicationContext(), SpeechConstant.APPID +"=5b33311b");

        //推送
        JPushInterface.setDebugMode(false); 	// 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);     		// 初始化 JPush
        String registrationID = JPushInterface.getRegistrationID(this);
//        bindJG(registrationID);
        //初始化九宫格控件
        NineGridView.setImageLoader(new GlideLoader());

        Frescoinit();
    }

    /** 九宫格glide 加载 */
    private class GlideLoader implements NineGridView.ImageLoader {

        @Override
        public void onDisplayImage(Context context, ImageView imageView, String url) {
//            RequestOptions options = new RequestOptions();
//            options.transforms(new CenterCrop(),new GlideCornerTransform(context,8)).dontAnimate();
            Glide.with(context).asBitmap().load(url).into(imageView);
        }

        @Override
        public Bitmap getCacheImage(String url) {
            return null;
        }


    }

    /**
     * Fresco图片参数初始化
     */
    private void Frescoinit() {
        //默认图片的磁盘配置
        DiskCacheConfig diskCacheConfig = DiskCacheConfig.newBuilder(this)
                .setBaseDirectoryPath(new File(Constants.FILE_KU_CALL))
                .setBaseDirectoryName("fresco")
                .build();
        ImagePipelineConfig config = ImagePipelineConfig.newBuilder(this)
                .setMainDiskCacheConfig(diskCacheConfig)
                .build();
        Fresco.initialize(this,config);
    }

    /**
     * 视频缓存
     * @param
     */

    public static HttpProxyCacheServer getProxy(Context context) {

        MApplication app = (MApplication) context.getApplicationContext();
        return app.proxy == null ? (app.proxy = app.newProxy()) : app.proxy;
    }

    private HttpProxyCacheServer newProxy() {
        return new HttpProxyCacheServer.Builder(this)
                .maxCacheSize(1024 * 1024 * 1024)       // 1 Gb for cache
                .build();
    }

    private void bindJG(String registrationID){
        String url = HttpConfig.PUSH;

        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("uid", SPUtils.getLoginUid());
        treeMap.put("deviceToken",registrationID);
        HttpClient.getInstance().postRxAndroidAES(url,treeMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData responseData) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void showToast(){
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                emitter.onNext("");
                emitter.onComplete();
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String s) {
                        Toast.makeText(getApplicationContext(),"当前账号已经在其他地方登陆",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void initOkhttpClient(){
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(15000L, TimeUnit.MILLISECONDS)
                .readTimeout(15000L, TimeUnit.MILLISECONDS)
                .addInterceptor(new LoggerInterceptor("TAG"))
//                .cookieJar(cookieJar1)
//                .hostnameVerifier(new HostnameVerifier()
//                {
//                    @Override
//                    public boolean verify(String hostname, SSLSession session)
//                    {
//                        return true;
//                    }
//                })
//                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                .build();
        HttpClient.initClient(okHttpClient);
    }

    public static MApplication getInstance(){
        return mInstance;
    }

    @GlideModule
    public class YourAppGlideModule extends AppGlideModule {
        @Override
        public void applyOptions(Context context, GlideBuilder builder) {
            int memoryCacheSizeBytes = 1024 * 1024 * 20; // 20mb
            builder.setMemoryCache(new LruResourceCache(memoryCacheSizeBytes));

            int bitmapPoolSizeBytes = 1024 * 1024 * 30; // 30mb
            builder.setBitmapPool(new LruBitmapPool(bitmapPoolSizeBytes));

            int diskCacheSizeBytes = 1024 * 1024 * 100;  //100 MB InternalDiskCacheFactory
            builder.setDiskCache(new InternalCacheDiskCacheFactory(context, diskCacheSizeBytes));
        }
    }
    /**
     * <p>连接服务器，在整个应用程序全局，只需要调用一次，需在  之后调用。</p>
     * <p>如果调用此接口遇到连接失败，SDK 会自动启动重连机制进行最多10次重连，分别是1, 2, 4, 8, 16, 32, 64, 128, 256, 512秒后。
     * 在这之后如果仍没有连接成功，还会在当检测到设备网络状态变化时再次进行重连。</p>
     *
     * @param token    从服务端获取的用户身份令牌（Token）。
     * @return RongIM  客户端核心类的实例。
     */
}
